//
//  ChangeBgViewController.swift
//  Matting
//  Created by JoyWT on 2022/3/4
//  
    

import UIKit
import opencv2
class ChangeBgViewController: BaseViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
    }
    override func pickedDone() {
        let od = Mat(uiImage: originalImage!) //原图
        let md = Mat(uiImage: maskImage!) //deaplab生成的mask图 ,黑色为前景区域
        //对mask区域进行凸起平滑处理,仅对车辆有效,其他有毛边的不适用
        let md1 = Mat()
        Imgproc.medianBlur(src: md, dst: md1, ksize: 41)

        //处理背景图片
        let nmd = Mat()
        Core.bitwise_not(src: md1, dst: nmd) //对mask图片取反 白色为前景区域
        
        //获取前景图像(抠图的部分)
        let nd = Mat()
        od.copy(to: nd, mask: nmd)
        
        let nbd = Mat(uiImage: UIImage(named: "beach.png")!)
        
//        let nbd = Mat(uiImage:originalImage!)

        let nnbd = Mat()
        //调整背景图和原图保持大小一致
        Imgproc.resize(src: nbd, dst: nnbd, dsize: Size2i(width: od.width(), height: od.height()))
        
        //高斯模糊
//        let gnnbd = Mat()
//        Imgproc.GaussianBlur(src: nnbd, dst: gnnbd, ksize: Size2i(width: 11, height: 11), sigmaX: 14, sigmaY: 2)
//        Imgproc.blur(src: nnbd, dst: gnnbd, ksize: Size2i(width: 101, height: 101))
        //对背景取mask区域置空
        let nnbd2 = Mat()
        Core.bitwise_and(src1: nnbd, src2: nnbd, dst: nnbd2, mask: md1)
        
        
        // 合并前景和背景图
        let ed = Mat()
        Core.add(src1: nd, src2: nnbd2, dst: ed)
        
        imageView.image = ed.toUIImage()
    }
    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destination.
        // Pass the selected object to the new view controller.
    }
    */

}
